package com.topisv.tms.web.focus;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.CustomerLead;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.service.CustomerLeadService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.lead.LeadUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/focusLeadOrdeno")
public class FocusLeadOrdenoController {
	
	private static final Logger log = LoggerFactory.getLogger(FocusLeadOrdenoController.class);
	
	private final static String init = "work/lead/LeadInit";
	private final static String installOrdeno="work/lead/LeadInstall";
	@Autowired
	private CustomersService customersService;
	@Autowired
	private CustomerLeadService customerLeadService;
	
	@RequestMapping(value = "init")
	public String toSynWeightPage(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customers=customersService.loadCustomerByAuthority(user);
		List<OrdenoSource> sources=customersService.findOrdenoSource(customers.get(0).getCustomerCode());
		model.addAttribute("sources", sources);
		model.addAttribute("customers", customers);
		return init;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "lead/{customerCode}/{type}")
	public String syn(@PathVariable(value = "customerCode") String customerCode,@PathVariable(value = "type") String type, Model model,
			ServletRequest request, RedirectAttributes redirectAttributes) {
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;
		List<String> sequence=null;
		try {
			log.info("订单设置开始");
			httpRequest = (HttpServletRequest) request;
			httpRequest.setCharacterEncoding("UTF-8");
			factory = new DiskFileItemFactory();
			upload = new ServletFileUpload(factory);

			items = upload.parseRequest(httpRequest);
			Iterator<FileItem> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (!item.isFormField() && item.getName() != null && !item.getName().equals("")) {
						// 获取Excel文件对象
						InputStream stream = item.getInputStream();
						if (item.getName().endsWith(".xls")) {// 解析xls
							rwb = new HSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							if(count>0){
								sequence=LeadUtil.getTop(rwb.getSheetAt(0));
							}
						} else if (item.getName().endsWith(".xlsx")) {// 解析xlsx
							rwb = new XSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							if(count>0){
								sequence=LeadUtil.getTop(rwb.getSheetAt(0));
							}
						}
					} else {
						model.addAttribute("message", "没有选择同步文件！");
						ShiroUser user = getShiroUser();
						List<Customers> customers=customersService.loadCustomerByAuthority(user);
						List<OrdenoSource> sources=customersService.findOrdenoSource(customers.get(0).getCustomerCode());
						model.addAttribute("sources", sources);
						model.addAttribute("customers", customers);
						return init ; 
					}
				}
				model.addAttribute("keys", sequence);
				model.addAttribute("customerCode", customerCode);
				model.addAttribute("type", type);
		} catch (Exception e) {
			
			model.addAttribute("message", "读取模板数据失败！");
			log.info("导入失败");
		}
		
		return installOrdeno;
	}
	
	
	
	
	@RequestMapping(value="ajaxLeadCusromerParam")
	public void ajaxLeadCusromerParam(@RequestParam(value="customerCode") String customerCode,
			@RequestParam(value="params") String params,
			@RequestParam(value="type") String type,HttpServletResponse response){
		JSONObject json=new JSONObject();
		Customers customers=null;
		PrintWriter out=null;
		try {
			out=response.getWriter();
			String [] strs = params.split(",");
			boolean blank=true;
			for(String v:strs){
				if(!isBlank(v)){blank=false;break;}
			}
			if(!blank){
				log.info("根据商家编码获取网点信息:"+customerCode);
				customers=customersService.findByCustomerCode(customerCode);
	
				if(null==customers){
					json.put("status", "-1");
					json.put("content", "该客户不存在");
					out.print(json.toString());
					log.error("该客户不存在("+customerCode+")");
					return;
				}
				CustomerLead customerLead=this.customerLeadService.findByCustomerCodeAndOrdenoSource(customerCode, type);
				if(customerLead==null){
					customerLead=new CustomerLead();
					customerLead.setCustomerCode(customerCode);
					customerLead.setOrdenoSource(type);
					customerLead.setStatus("pending");
					customerLead.setCreateTime(new Date());
				}
				customerLead.setParams(params);
				this.customerLeadService.save(customerLead);
				
				json.put("content", "设置成功");
				json.put("status", "1");
				out.print(json.toString());
			} else {
				json.put("status", "0");
				json.put("content","没有有效的订单模板字段，设置失败");
				out.print(json.toString());
				log.error(customerCode+"没有有效的订单模板字段，设置失败");
			}
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			if(null !=out)out.print(json.toString());
			log.error(customerCode+"订单模板设置失败 ",e);
		}
	}
	public boolean isBlank(String val){
		return null == val || val.trim().length()==0;
	}
	
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

}
